import React from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, message, Button } from 'antd';
import _ from 'lodash';
import AddAttrModal from './addAttr';
import { formItemLayout } from '../common';

const FormItem = Form.Item;
const mainProps = [
  'name', 'id', 'packageSize', 'price', 'guide',
];

const map = {
  create: {
    title: '新建任务',
    button: '新建',
    effect: 'task/create',
    success: '创建任务成功',
  },
  edit: {
    title: '更新任务',
    button: '更新',
    effect: 'task/edit',
    success: '更新任务成功',
  },
};

// 只支持自定义Input，别的不支持

const defaultValues = [
  {
    label: '名称',
    id: 'name',
    rules: [
      {
        required: true,
        message: '名称不能为空',
      },
    ],
    component: <Input placeholder="请输入名称" />,
  },
  {
    label: '包数量',
    id: 'packageSize',
    rules: [
      {
        required: true,
        message: '包数量不能为空',
      },
    ],
    component: <Input placeholder="请输入包数量" type="number" />,
  },
  {
    label: '包价格',
    id: 'price',
    rules: [
      {
        required: true,
        message: '包价格不能为空',
      },
    ],
    component: <Input placeholder="请输入包价格" type="number" />,
  },
  {
    label: '导航页',
    id: 'guide',
    component: <Input placeholder="请输入导航页" />,
  },
];

class TaskModal extends React.Component {
  constructor(p) {
    super(p);
    this.handleOK = this.handleOK.bind(this);
    this.handleAddAttr = this.handleAddAttr.bind(this);
    this.handleFinish = this.handleFinish.bind(this);
    this.deleteAttr = this.deleteAttr.bind(this);

    this.state = {
      values: _.cloneDeep(defaultValues), // 默认的可设置的key值，其实可以叫做keys
      visible: false,
    };
    // 设置选项值
    const { type, record } = this.props;
    if (type === 'edit' && record) {
      let settings = _.cloneDeep(record.settings);
      delete record.settings;
      // 设置默认属性的值
      Object.keys(record).forEach((key) => {
        const index = _.findIndex(this.state.values, o => o.id === key);
        if (index >= 0) {
          this.state.values[index].initialValue = record[key];
        }
      });
      // 设置settings的值
      if (settings) {
        if (typeof settings === 'string') {
          settings = JSON.parse(settings);
        }
        Object.keys(settings).forEach((key) => {
          this.state.values.push({
            label: key,
            id: key,
            initialValue: settings[key],
            component: <Input placeholder={`请输入${key}`} />,
          });
        });
      }
    }
  }

  // 添加新的属性
  handleAddAttr() {
    this.setState({
      visible: true,
    });
  }

  // 处理点击确认之后的事件
  handleOK() {
    const {
      validateFields,
      getFieldsValue,
    } = this.props.form;
    validateFields((err) => {
      if (!err) {
        const value = getFieldsValue();
        const { dispatch, type, record } = this.props;
        dispatch({
          type: map[type].effect,
          payload: {
            value: _.merge({ id: _.get(record, 'id') }, value),
            onEnd: (error) => {
              if (error) {
                return message.error(error);
              }
              message.success(map[type].success);
              this.props.onFinish();
            },
          },
        });
      }
    });
  }

  // 处理结束事件
  handleFinish(value) {
    this.setState({
      visible: false,
    });

    if (value) {
      this.state.values.push({
        label: value.key,
        id: value.key,
        component: <Input placeholder={`请输入${value.key}`} />,
      });

      this.setState({});
    }
  }

  deleteAttr() {
    const attr = window.prompt('请输入属性id');
    if (mainProps.indexOf(attr) >= 0) {
      return message.error('不能删除主要属性');
    }
    let values = this.state.values;
    values = values.filter(item => item.id !== attr);
    this.setState({
      values,
    });
  }

  render() {
    const { form, visible, onFinish, loading, type } = this.props;
    const { getFieldDecorator } = form;
    const { values } = this.state;
    return (
      <div>
        {
          this.state.visible &&
          <AddAttrModal
            visible={this.state.visible}
            onFinish={this.handleFinish}
            keys={values.map(o => o.id)}
          />
        }
        <Modal
          title={map[type].title}
          visible={visible}
          onCancel={onFinish}
          okText={map[type].button}
          onOk={this.handleOK}
          confirmLoading={loading[map[type].effect]}
        >
          <Form layout="horizontal">
            {
              values.map((item) => {
                return (
                  <FormItem label={item.label} hasFeedback {...formItemLayout}>
                    {
                      getFieldDecorator(
                        item.id, {
                          rules: item.rules,
                          initialValue: item.initialValue,
                        },
                      )(item.component)
                    }
                  </FormItem>
                );
              })
            }
          </Form>
          <Button
            type="primary"
            onClick={this.handleAddAttr}
          >
            + 添加属性
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button
            type="danger"
            onClick={this.deleteAttr}
          >
            - 删除属性
          </Button>
        </Modal>
      </div>
    );
  }
}

TaskModal.defaultProps = {
  onFinish: () => null,
  loading: false,
  visible: false,
  type: 'create',
  record: null,
};

export default connect(state => state)(Form.create()(TaskModal));
